<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useColumns } from "./columns";
import router from "@/router";
import { Experiment } from "@/api/LabExperimentApi";
import type { PaginationProps } from "@pureadmin/table";
import { message } from "@/utils/message";
// import selectDir from "./selectDir.vue";
import { downloadInstanceData } from "@/api/LabInstanceApi";
// import { ErrorCodes } from "vue";
// const { toDetail, router } = useDetail();

const tableRef = ref();

const {
  loading,
  columns,
  loadingConfig,
  adaptiveConfig,
  onSizeChange,
  onCurrentChange
} = useColumns();

const props = defineProps({
  labExperimentData: {
    type: Object as () => Experiment
  },
  labPlatformData: {
    type: Array
  },
  newPagination: {
    type: Object as () => PaginationProps
  }
});

// const downFileBlob = (fileName, fileBlob) => {
//   const fileNameGroup = fileName.split(".");
//   const fileType = fileNameGroup[fileNameGroup.length - 1].toLowerCase();
//   const blob = new Blob([fileBlob], {
//     type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
//   }); //处理文档流
//   const elink = document.createElement("a");
//   elink.download = fileName;
//   elink.style.display = "none";
//   elink.href = URL.createObjectURL(blob);
//   document.body.appendChild(elink);
//   elink.click();
//   URL.revokeObjectURL(elink.href); // 释放URL 对象
//   document.body.removeChild(elink);
// };

const selectedFolder = ref("");

const clickExport = async row => {
  loading.value = true;
  downloadInstanceData({
    expInstId: row.id
  }).then(response => {
    console.log("response", response);
    if (response.errorCode || !response) {
      message(`导出失败：${response.message}`, { type: "error" });
      loading.value = false;

      return;
    }

    const blob = new Blob([response], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
    });
    const fileName = `${row.name}_${row.id}_历史数据.xlsx`;
    if ("download" in document.createElement("a")) {
      // 非IE下载
      const elink = document.createElement("a");
      elink.download = fileName;
      elink.style.display = "none";
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      document.body.removeChild(elink);
    } else {
      // IE10+下载
      navigator.msSaveBlob(blob, fileName);
    }
    loading.value = false;
  });
  // if (res.errorCode) {
  //   message(`${res.message}`, { type: "error" });
  // } else {
  //   console.log(res.headers);
  //   const fileName = res.headers["content-disposition"].replace(
  //     "attachment;filename=",
  //     ""
  //   );
  //   downFileBlob(fileName, res.data);
  //   message("导出成功", { type: "success" });
  //   loading.value = false;
  // }
};

const openFolderDialog = () => {
  const input = document.createElement("input");
  input.type = "file";
  // input.webkitdirectory = true;
  // input.directory = true;
  input.webkitdirectory = true;
  input.accept = ".";
  input.addEventListener("change", event => {
    const folderPath = event.target.files[0].path;
    selectedFolder.value = folderPath;
  });
  console.log("input", input);
  input.click();
};

const uploadClick = () => {
  if (!selectedFolder.value) {
    alert("Please select a folder.");
    return;
  }
  // 执行上传逻辑
};

// const disabled = ref(false);
// const ExpData = ref();
onMounted(async () => {
  //将props.labExperimentData的值赋给ExpData
  // ExpData.value = props.labExperimentData;
  // ExpData.value = toRef(props, "labExperimentData");
  // const res = await getRunningExperiments();
  //遍历labExperimentData，如果item的state是20那disabled就为false
  // if (!res.errorCode) {
  //   if (res.data) {
  //     console.log("hhhhh");
  //     for (const item in ExpData.value) {
  //       console.log("item", item);
  //       if (item.state == 20) {
  //         item.disabled = false;
  //       } else {
  //         item.disabled = true;
  //       }
  //     }
  //   }
  // } else {
  //   message(`${res.message}`, { type: "error" });
  // }
});

const emit = defineEmits(["delete-item"]);

const handleClickDelete = async expID => {
  emit("delete-item", expID);
};

const clickView = row => {
  if (row.state == 20) {
    //跳转至实验历史监控
    localStorage.setItem(
      "defaultMonitorQuery",
      JSON.stringify({
        configId: row.expPlatformId,
        id: row.id,
        hisFlag: 1
      })
    );

    router.push({
      name: "Monitor",
      query: {
        configId: row.expPlatformId,
        id: row.id,
        hisFlag: 1
      }
    });
  } else {
    //跳转至实验实例监控
    localStorage.setItem(
      "defaultMonitorQuery",
      JSON.stringify({
        configId: row.expPlatformId,
        id: row.id,
        expFlag: 1
      })
    );
    router.push({
      name: "Monitor",
      query: { configId: row.expPlatformId, id: row.id, expFlag: 1 }
    });
  }
};

// watch(
//   () => props.labExperimentData,
//   newVal => {
//     ExpData.value = newVal;
//   }
// );

// watch(
//   () => props.labExperimentData,
//   newVal => {
//     for (const item in newVal) {
//       const exist = JSON.parse(
//         localStorage.getItem(`settingList${newVal[item].id}`)
//       );
//       if (exist && exist.value) {
//         continue;
//       }
//       localStorage.removeItem(`settingList${newVal[item].id}`);
//     }
//   }
// );

// function handleClick(row) {
//   console.log(
//     "%crow===>>>: ",
//     "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
//     row
//   );
// }
const formatTimeDiff = (endTime, startTime) => {
  console.log("endTime", endTime);
  if (!endTime) {
    endTime = new Date();
  }
  const timeDiff = endTime.getTime() - startTime.getTime();

  const hours = Math.floor(timeDiff / (1000 * 60 * 60));
  const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000);

  // const Time = hours ? hours + "小时" : "";
  // const j = minutes ? (minutes < 10 ? "0" + minutes : minutes) : "";
  // const k=seconds?(seconds < 10 ? "0" + seconds : seconds) "秒" : "";
  // 格式化时间
  return `${hours ? hours + "小时" : ""}${
    minutes ? (minutes < 10 ? "0" + minutes : minutes) + "分钟" : ""
  }${seconds ? (seconds < 10 ? "0" + seconds : seconds) + "秒" : "0秒"}`;
};
</script>

<template>
  <!-- {{ ExpData }} -->
  <!-- {{ labExperimentData }} -->
  {{ selectedFolder }}
  <pure-table
    ref="tableRef"
    border
    adaptive
    :adaptiveConfig="adaptiveConfig"
    row-key="id"
    alignWhole="center"
    showOverflowTooltip
    :loading="loading"
    :loading-config="loadingConfig"
    :data="
      labExperimentData.slice(
        (newPagination.currentPage - 1) * newPagination.pageSize,
        newPagination.currentPage * newPagination.pageSize
      )
    "
    :columns="columns"
    :pagination="newPagination"
    @page-size-change="onSizeChange"
    @page-current-change="onCurrentChange"
  >
    <template #duration="{ row }">
      {{
        formatTimeDiff(
          new Date(row.endTime) > new Date()
            ? new Date()
            : new Date(row.endTime),
          new Date(row.startTime)
        )
      }}
    </template>
    <template #expPlatformId="{ row }">
      {{
        labPlatformData.find(obj => {
          return obj.id === row.expPlatformId;
        }).name
      }}
    </template>
    <template #state="{ row }">
      <el-tag
        effect="light"
        :type="
          row.state === 20
            ? 'danger'
            : row.state === 10
            ? ''
            : row.state === 0
            ? 'warning'
            : 'info'
        "
      >
        {{
          row.state === 20
            ? "已结束"
            : row.state === 10
            ? "正在运行"
            : row.state === 0
            ? "未开始"
            : row.state
        }}
      </el-tag>
    </template>
    <template #operation="{ row }">
      <el-button link type="primary" size="small" @click="clickView(row)">
        查看
      </el-button>
      <el-button link type="primary" @click="clickExport(row)" size="small"
        >导出</el-button
      >

      <el-button
        :disabled="row.state === 10"
        link
        type="primary"
        size="small"
        @click="handleClickDelete(row.id)"
        >删除</el-button
      >
    </template>
  </pure-table>
  <!-- <div>
    <el-button @click="openFolderDialog">选择文件夹</el-button>
    <el-button @click="uploadClick">上传</el-button>
  </div> -->
</template>
